import { Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Menu } from './entities/menu.entity'
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { StatusText } from 'src/types/enum';
import { SearchMenuDto } from './dto/search-menu.dto';


@Injectable()
export class MenusService {
  private menuTypeLabel = {
    ['1']: "模块",
    ['2']: "页面",
    ['3']: "按钮",
  }
  constructor(@InjectRepository(Menu) private menuRepository: Repository<Menu>) {

  }


  create(createMenuDto: CreateMenuDto) {
    return this.menuRepository.save(createMenuDto);
  }

  async findAll(searchMenuDto: SearchMenuDto) {
    let search = {
      where: {},
    }
    if (searchMenuDto.name) {
      search.where = {
        name: Like(`%${searchMenuDto.name}%`)
      }
    }
    const result = await this.menuRepository.find(search);
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: this.buildTree(result, 0)
      }
    }
  }

  private buildTree(menus: Menu[], parentId: number | null): Menu[] {
    return menus
      .filter(menu => menu.parent_id === parentId)
      .map(menu => ({
        ...menu,
        typeLabel: this.menuTypeLabel[menu.type],
        children: this.buildTree(menus, menu.id),
      }));
  }

  findOne(id: number) {
    return this.menuRepository.find({ where: { id } });
  }

  update(id: number, updateMenuDto: UpdateMenuDto) {
    return this.menuRepository.update(id, updateMenuDto);
  }

  remove(id: number) {
    return this.menuRepository.delete({ id });
  }
}
